package com.huluobo.apps.view

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppsEntity
import com.huluobo.apps.entity.AppsEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.HttpType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/3/13.
 */
@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    val list = remember {
        SnapshotStateList<AppsEntityItem>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    var launch by remember {
        mutableStateOf(false)
    }

    var currentProgress by remember {
        mutableStateOf(0f)
    }

    val scope = rememberCoroutineScope()

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        if (it.type == HttpType.DEFAULT) {
                            list.addAll(it.data as AppsEntity)
                        }

                        if (it.type == HttpType.DOWNLOAD) {
                            isShowProgress = false
                            ToastUtils.showLong("下载成功")
                            navHostController.popBackStack()
                        }
                    }
                }
            }
        }
        vm.sendIntent(AppsIntent.GetApps)
    })

    Column(Modifier.padding(10.dp)) {
        Box(contentAlignment = Alignment.CenterStart, modifier = Modifier.padding(20.dp)) {
            Text(text = "在线应用", textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", modifier = Modifier.clickable {
                navHostController.popBackStack()
            })
        }
        Spacer(modifier = Modifier.height(10.dp))
        LazyVerticalGrid(
            columns = GridCells.Fixed(3),
            verticalArrangement = Arrangement.spacedBy(10.dp),
            horizontalArrangement = Arrangement.spacedBy(10.dp),
            content = {
                items(list) {
                    AppsItem(appsEntityItem = it, vm, onClick = {
                        isShowProgress = true
                    }, longClick = {
                        launch = true
                        scope.launch {
                            for (i in 1..100) {
                                currentProgress = i.toFloat() / 100
                                delay(100)
                            }
                            launch = false
                            ToastUtils.showLong("安装成功")
                        }
                    })
                }
            })
        if (isShowProgress) {
            CircularProgressIndicator()
        }
        if (launch) {
            LinearProgressIndicator(
                progress = currentProgress,
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 40.dp)
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appsEntityItem: AppsEntityItem, vm: AppsViewModel, onClick: () -> Unit, longClick: () -> Unit) {
    var isShow by remember {
        mutableStateOf(false)
    }

    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    Column(modifier = Modifier.combinedClickable(
        onClick = {
            isShow = true
        }, onLongClick = {
            longClick()
        }
    ), horizontalAlignment = Alignment.CenterHorizontally) {
        AsyncImage(model = appsEntityItem.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Text(text = appsEntityItem.appName)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            TextButton(onClick = {
                vm.sendIntent(
                    AppsIntent.DownloadApk(
                        appsEntityItem.apkUrl,
                        File(file, appsEntityItem.appName + ".apk")
                    )
                )
                isShow = false
                onClick()
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = { isShow = false }) {
                Text(text = "取消")
            }
        }, title = { Text(text = "下载提醒") }, text = {
            Text(text = "是否要下载${appsEntityItem.appName}吗?")
        })
    }
}